package leetcode.editor.cn.q1xx

import leetcode.editor.cn.TreeNode
import kotlin.math.abs
import kotlin.math.max

class Q110 {
    fun isBalanced(root: TreeNode?): Boolean {
        return getDepth(root) >=0
    }

    fun getDepth(node: TreeNode?): Int {
        if (node == null)
            return 0
        val leftDepth = getDepth(node.left)
        val rightDepth = getDepth(node.right)
        return if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth - rightDepth) > 1) {
            -1
        } else {
            max(leftDepth, rightDepth) + 1
        }
    }
}